package com.hrm.social.controller;

import com.hrm.common.controller.BaseController;
import com.hrm.common.entity.PageResult;
import com.hrm.common.entity.Result;
import com.hrm.common.entity.ResultCode;
import com.hrm.domain.social_security.*;
import com.hrm.social.client.SystemFeignClient;
import com.hrm.social.service.ArchiveService;
import com.hrm.social.service.CompanySettingsService;
import com.hrm.social.service.PaymentItemService;
import com.hrm.social.service.UserSocialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/social_securitys")
public class SocialSecuritysController extends BaseController {

    @Autowired
    private CompanySettingsService companySettingsService;
    @Autowired
    private UserSocialService userSocialService;
    @Autowired
    private PaymentItemService paymentItemService;
    @Autowired
    private ArchiveService archiveService;
    @Autowired
    private SystemFeignClient systemFeignClient;

    /**
     * 查询企业是否设置过社保
     */
    @RequestMapping(value = "/settings", method = RequestMethod.GET)
    public Result settings() {
        CompanySettings companySettings = companySettingsService.findById(companyId);
        return new Result(ResultCode.SUCCESS, companySettings);
    }

    @RequestMapping(value = "/settings", method = RequestMethod.POST)
    public Result saveSettings(@RequestBody CompanySettings companySettings) {
        companySettingsService.save(companySettings);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 分页查询员工社保信息列表
     *
     * @param map（包括page和pagesize）
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Result list(@RequestBody Map<String, Object> map) {
        Integer page = (Integer) map.get("page");
        Integer pageSize = (Integer) map.get("pageSize");
        PageResult<Map<String, Object>> pageResult = userSocialService.findAll(page, pageSize, companyId);
        return new Result(ResultCode.SUCCESS, pageResult);
    }

    /**
     * 根据用户id查询用户数据和社保数据
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        Map<String, Object> map = new HashMap<>();
        //根据id查询用户数据
        Result userResult = systemFeignClient.findById(id);
        Object user = userResult.getData();
        map.put("user", user);
        //根据id查询社保数据
        UserSocialSecurity userSocialSecurity = userSocialService.findById(id);
        map.put("userSocialSecurity", userSocialSecurity);
        return new Result(ResultCode.SUCCESS, map);
    }

    /**
     * 根据城市id查询城市的参保项目
     */
    @RequestMapping(value = "/payment_item/{id}", method = RequestMethod.GET)
    public Result findPaymentItem(@PathVariable String id) {
        List<CityPaymentItem> list = paymentItemService.findAllByCityId(id);
        return new Result(ResultCode.SUCCESS, list);
    }

    /**
     * 保存或更新用户社保
     */
    @RequestMapping(value = "/save", method = RequestMethod.PUT)
    public Result saveUserSocialSecritys(@RequestBody UserSocialSecurity userSocialSecurity) {
        userSocialService.save(userSocialSecurity);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 查询月份归档细节
     * /history/201907?yearMonth=201907&opType=1
     * opType=1:表示当月，其他值为历史归档
     */
    @RequestMapping(value = "/history/{yearMonth}", method = RequestMethod.PUT)
    public Result historyDetil(@PathVariable String yearMonth, int opType) {
        List<ArchiveDetail> list = new ArrayList<>();
        if (opType == 1) {
            //未归档
            list = archiveService.getReport(companyId, yearMonth);
        } else {
            //已归档
            //根据月份和企业id查询归档历史
            Archive archive = archiveService.findArchive(companyId, yearMonth);
            if (archive != null) {
                list = archiveService.findAllDetailByArchiveId(archive.getId());
            }
        }
        return new Result(ResultCode.SUCCESS, list);
    }

    /**
     * 数据归档
     * /history/201907/archive
     */
    @RequestMapping(value = "/history/{yearMonth}/archive", method = RequestMethod.POST)
    public Result archive(@PathVariable String yearMonth) {
        archiveService.archive(yearMonth, companyId);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 新建归档报表，切换到下个月
     * /history/201908/newReport
     */
    @RequestMapping(value = "/history/{yearMonth}/archive", method = RequestMethod.PUT)
    public Result newArchive(@PathVariable String yearMonth) {
        //settings表中根据企业查询
        CompanySettings companySettings = companySettingsService.findById(companyId);
        if (companySettings == null) {
            companySettings = new CompanySettings();
        }
        companySettings.setCompanyId(companyId);
        companySettings.setDataMonth(yearMonth);
        companySettings.setIsSettings(1);
        companySettingsService.save(companySettings);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 查询某年内的历史归档记录（archive和detail信息）
     * /histories/{2019}/list
     */
    @RequestMapping(value = "/histories/{year}/list", method = RequestMethod.GET)
    public Result histories(@PathVariable String year) {
        List<Archive> list = archiveService.findArchiveByYear(companyId, year);
        return new Result(ResultCode.SUCCESS, list);
    }

    /**
     * 向薪资管理模块提供的接口
     *  根据用户id和考情年月查询用户的社保记录详情
     * /histories/data/{yearMonth}
     * 重写：/histories/archiveDetail/{userId}/{yearMonth}
     */
    @RequestMapping(value = "/histories/archiveDetail/{userId}/{yearMonth}", method = RequestMethod.GET)
    public Result historiesData(@PathVariable String userId,@PathVariable String yearMonth) {
        ArchiveDetail detail = archiveService.findUserArchiveDetail(userId, yearMonth);
        return new Result(ResultCode.SUCCESS,detail);
    }
}
